<template>
  <m-layout class="farm" title="" color="#fff" gap="0 24" :goBack="false" barBg="unset">
    <!-- 顶部 -->
    <view slot="back">
      <m-image2 :size="[198, 40]" src="../../static/images/pages/farm/farmTop.png" />
    </view>
    <view slot="right" class="flex" @click="Jump('/pages/farm/record/index')">
      <m-icon type="recive" size="40" />
      <text class="fs24 ml-4 text-black">領取記錄</text>
    </view>

    <!-- 主要内容 -->
    <view class="flex-column">
      <!-- 欢迎文字 -->
      <view class="flex mb-20">
        <m-icon type="coin" size="30" />
        <text class="fs22 ml-12">歡迎來到農場，快人一步，解鎖專屬獎勵！</text>
      </view>

      <!-- ✅ 今日广告投放进度 -->
      <view class="adProgress mb-20" v-if="config601 > 0">
        <view class="adProgressTop flex ai-center jc-space-between">
          <view class="flex ai-center">
            <!-- 播放图标 -->
            <view class="adIcon">
              <view class="adIconInner"></view>
              <view class="playTriangle"></view>
            </view>
            <text class="adTitle">当前廣告投放</text>
          </view>
          <text class="adCount" :class="adCount >= config601 ? 'text-green' : ''">
            {{ adCount }}/{{ config601 }}
          </text>
        </view>
        
        <!-- 进度条 -->
        <view class="progressBar mt-16">
          <view class="progressFill" :style="{ width: adProgressPercent + '%' }"></view>
        </view>
        
        <!-- 提示文字 -->
        <view class="adTip mt-8" v-if="adCount < config601">
          <text>還需觀看 {{ config601 - adCount }} 次廣告才能領取</text>
        </view>
        <view class="adTipComplete mt-8" v-else>
          <text>✅ 已滿足觀看條件，果實已領取</text>
        </view>
      </view>

      <!-- 累计收获 -->
      <m-block class="totalCount flex fs26 pl-20 jc-center">
        <m-icon type="coin2" size="30" />
        <text class="mlr-12">累計已收穫</text>
        <view class="flex">
          <text>{{ receiveData.receiveCount }}</text>
          <text class="ml-4">果實</text>
        </view>
      </m-block>

      <!-- 农场图片和状态 -->
      <view class="imgBox flex-column jc-center plr-32 pt-60">
        <m-image2 :size="[627, 653]" src="../../static/images/pages/farm/tree.png" />
        <text class="fs21 farmState flex jc-center" :class="[receiveData.state == 1 ? '' : 'text-red']">
          {{ receiveData.state == 1 ? '生產中...' : '已結束' }}
        </text>
      </view>

      <!-- 按钮区域 -->
      <view class="btnBox flex-column mt-20">
        <!-- 下次领取时间 -->
        <view class="flex jc-center fs24 mtb-12 text-white" v-if="receiveData.receiveNext">
          <text>下一次領取:</text>
          <view class="flex">
            <text>{{ receiveData.receiveNext.replace('T', ' ').slice(0, 16) }}</text>
          </view>
        </view>

        <!-- 领取按钮 -->
        <view class="recBtn flex jc-center ai-baseline pt-24" @click="handleUseFeature()">
          <view class="flex" v-if="Number(startTime) > 0">
            <mCountDown color="#fff" :timestamp="startTime" />
          </view>
          <view class="flex text-white" v-else>
            <text v-if="receiveData.receive == 1">領取</text>
          </view>
          <text class="fs26 ml-8 text-white">{{ receiveData.receiveNum }}</text>
          <text class="fs24 text-white">果實</text>
        </view>
      </view>
    </view>

    <!-- 成功弹窗 -->
    <m-dialog title="" :showCancel="false" :isShow="tipsShow" @handleCancel="tipsShow = false"
      @handleConfirm="tipsShow = false">
      <view class="ptb-48 flex-column jc-center ai-center">
        <m-image2 :size="[260, 260]" src="../../static/images/pages/farm/success.png" />
        <text>領取成功</text>
        <view class="flex text-primary fs26 mt-12">
          <text>收穫</text>
          <text>{{ receiveData.receiveNum }}</text>
          <text class="fs24">果實</text>
        </view>
      </view>
    </m-dialog>
  </m-layout>
</template>

<script>
import { mapState } from 'vuex';
import { myFruit, Receive } from '@/api/Activetion.js';
import { creditdetal } from '@/api/Trade.js';
import mCountDown from '@/components/m-countdown/index.vue';
import rewardVideoAdManager from '@/utils/rewardVideoAdManager/index.js';

export default {
  components: {
    mCountDown
  },
  data() {
    return {
      credittype: '41', // 农场收益
      receiveData: {},
      typeid: 1,
      listArr: [],
      pageIndex: 1,
      pageSize: 10,
      pageCount: 1,
      isLoading: false,
      startTime: 0,
      tipsShow: false,
      adCount:0 ,  // 今日已看广告
      _needRefreshAfterAd: false,  // ✅ 标记广告完成后是否需要刷新
      _lastAdCompleteTime: 0,  // ✅ 上次广告完成的时间戳
      lastAdWatchedAt: 0, // ✅ 最近一次完整观看广告的时间戳（毫秒）
    };
  },

  onLoad() {
    console.log('农场页面加载');
  },

  onReady() {
    console.log('农场页面准备完成，初始化广告管理器');
    this.initAdManager();
  },

  computed: {
    ...mapState({
      userInfo: (state) => state.user.userinfo,
      coinConfig: (state) => state.general.coinConfig,
      config: (state) => state.general.config,
      timespan: (state) => state.general.timespan
    }),
    // ✅ 每日需要观看广告次数
    config601() {
      return Number(this.config[601] || 10);
    },
    // ✅ 广告观看进度百分比
    adProgressPercent() {
      if (this.config601 === 0) return 0;
      return Math.min((this.adCount / this.config601) * 100, 100);
    },
    // ✅ 是否满足观看条件
    canReceive() {
      return this.adCount >= this.config601;
    },
    // ✅ 广告观看间隔（单位秒）
    adInterval() {
      return Number(this.config[602] || 300);
    }
  },

  onShow() {
    console.log('农场页面显示');

    // ✅ 页面显示时预加载广告（确保6小时后能快速显示广告）
    rewardVideoAdManager.preload();

    // ✅ 恢复本地缓存的广告时间戳
    const cachedLastAd = Number(uni.getStorageSync('lastAdWatchedAt') || 0);
    if (cachedLastAd && (!this.lastAdWatchedAt || cachedLastAd > this.lastAdWatchedAt)) {
      this.lastAdWatchedAt = cachedLastAd;
    }

    // ✅ 如果广告完成后需要刷新，延迟刷新数据（等待后端回调完成）
    if (this._needRefreshAfterAd) {
      console.log('✅ 广告完成，延迟刷新数据');
      this._needRefreshAfterAd = false;
      
      uni.showLoading({ title: '更新中...', mask: true });
      
      setTimeout(async () => {
        try {
          await this.receiveDataFn();
          const newAdCount = this.adCount;
          const targetCount = this.config601;
          console.log(`✅ 广告观看完成，进度更新: ${newAdCount}/${targetCount}`);
          
          if (newAdCount >= targetCount) {
            console.log('✅ 已达到观看要求，自动领取果实');
            await this.ReceiveFn();
          } else {
            // ✅ 没有达到要求，也需要刷新列表
            this.getData();
          }
        } finally {
          uni.hideLoading();
        }
      }, 500);
    } else {
      // ✅ 正常刷新
      this.reset();
    }
  },

  onUnload() {
    console.log('农场页面卸载，销毁广告管理器');
    rewardVideoAdManager.destroy();
  },

  methods: {
    /**
     * 初始化广告管理器
     */
    initAdManager() {
      console.log('=== 开始初始化广告管理器 ===');

      // 检测环境（与原始代码保持一致）
      const isApp = rewardVideoAdManager.checkEnvironment();

      // 设置回调函数
      const self = this;  // ✅ 保存 this 引用
      rewardVideoAdManager.setCallbacks({
        onAdComplete: (res) => {
          // ✅ 短时间内只允许执行一次（1秒内）
          const now = Date.now();
          const timeSinceLastCall = now - (self._lastAdCompleteTime || 0);
          
          if (self._lastAdCompleteTime > 0 && timeSinceLastCall < 1000) {
            console.log(`⚠️ 1秒内有重复调用，跳过。距离上次: ${timeSinceLastCall}ms`);
            return;
          }
          
          console.log(`✅ 广告观看完成回调（距离上次: ${timeSinceLastCall}ms）`);
          self._lastAdCompleteTime = now;

          // ✅ 记录最近一次完整观看广告的时间戳
          self.lastAdWatchedAt = now;
          uni.setStorageSync('lastAdWatchedAt', now);
          
          // ✅ 只设置标记，不刷新数据，由 onShow 统一处理
          self._needRefreshAfterAd = true;
        },
        onAdIncomplete: (res) => {
          console.log('❌ 广告观看未完成回调');
        },
        onH5Fallback: () => {
          console.log('H5环境降级回调');
        },
        onFallback: () => {
          console.log('广告失败降级回调');
          // this.ReceiveFn();
          // this.Toast('廣告加載失敗，請20分鐘後重試');
        }
      });

      // ✅ 如果是App环境，初始化广告（不传userId，稍后在显示时动态传入）
      if (isApp) {
        console.log('开始初始化广告...');
        rewardVideoAdManager.init();
      } else {
        console.log('非App环境，跳过广告初始化');
      }
      console.log('=== 广告管理器初始化完成 ===');
    },

    /**
     * ✅ 用户点击领取 - 优化后的逻辑
     */
    async handleUseFeature() {
      console.log('用户点击领取按钮');

      // 检查是否到领取时间
      if (this.receiveData.receive !== 1) {
        return this.Toast('未到领取时间');
      }

      // ✅ 检查是否满足观看广告次数要求
      if (this.config601 > 0 && this.adCount < this.config601) {
        const needMore = this.config601 - this.adCount;
        
        // 提示用户需要先观看广告
        uni.showModal({
          title: '提示',
          content: `您還需要觀看 ${needMore} 次廣告才能領取果實\n\n當前進度: ${this.adCount}/${this.config601}`,
          confirmText: '觀看廣告',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              console.log('用户确认观看广告，开始显示广告');
              
              const now = Date.now();
              const lastWatch = this.lastAdWatchedAt || Number(uni.getStorageSync('lastAdWatchedAt') || 0);
              const intervalMs = this.adInterval * 1000;
              if (lastWatch && now - lastWatch < intervalMs) {
                const remainSeconds = Math.ceil((intervalMs - (now - lastWatch)) / 1000);
                const remainMinutes = Math.ceil(remainSeconds / 60);
                const hint = remainSeconds > 60 ? `${remainMinutes} 分鐘` : `${remainSeconds} 秒`;
                this.Toast(`請稍後 ${hint} 再觀看下一個廣告`);
                return;
              }

              // ✅ 获取用户ID并传入
              const userId = this.userInfo?.userid || 'testuser';
              console.log('显示广告，使用 userId:', userId);
              rewardVideoAdManager.showRewardedVideoAd({ userId });
            }
          }
        });
        return;
      }

      // ✅ 已经满足观看要求，直接领取
      if (this.canReceive || this.config601 === 0) {
        console.log('已满足观看要求，开始领取果实');
        await this.ReceiveFn();
      } else {
        // 兜底：如果配置有问题，也允许领取
        console.log('配置检查通过，开始领取果实');
        await this.ReceiveFn();
      }
    },

    /**
     * 初始化数据
     */
    reset() {
      console.log('重置页面数据');
      this.pageCount = 1;
      this.pageIndex = 1;
      this.receiveDataFn();
      this.getData();
    },

    /**
     * 获取时间戳
     */
    getTimestamp(timeStr) {
      const timestamp = Math.floor(new Date(timeStr).getTime() / 1000);
      this.startTime = Number(timestamp) - this.timespan;
    },

    /**
     * ✅ 领取果实 - 优化后
     */
    async ReceiveFn() {
      console.log('开始领取果实');

      const { success, msg } = await Receive();
      this.Toast(msg);

      if (!success) {
        console.log('领取失败:', msg);
        return;
      }

      console.log('领取成功');
      this.tipsShow = true;
      
      // ✅ 领取成功后刷新数据（包括广告计数）
      this.reset();
    },

    /**
     * 获取农场数据
     */
    async receiveDataFn() {
      console.log('获取农场数据');

      try {
        const { success, msg, data } = await myFruit();

        if (!success) {
          console.log('获取农场数据失败:', msg);
          return Promise.resolve();
        }

        this.receiveData = data;
        this.adCount = Number(data.adCount || 0);
        this.getTimestamp(data.receiveNext);

        if (data.lastAdTime) {
          const serverTime = Number(data.lastAdTime);
          let lastAdTimestamp = NaN;
          if (!Number.isNaN(serverTime)) {
            lastAdTimestamp = serverTime < 1e12 ? serverTime * 1000 : serverTime;
          } else {
            const parsed = Date.parse(data.lastAdTime);
            if (!Number.isNaN(parsed)) {
              lastAdTimestamp = parsed;
            }
          }
          if (!Number.isNaN(lastAdTimestamp) && lastAdTimestamp > 0) {
            this.lastAdWatchedAt = lastAdTimestamp;
            uni.setStorageSync('lastAdWatchedAt', lastAdTimestamp);
          }
        } else {
          const cachedLastAd = Number(uni.getStorageSync('lastAdWatchedAt') || 0);
          if (cachedLastAd && (!this.lastAdWatchedAt || cachedLastAd > this.lastAdWatchedAt)) {
            this.lastAdWatchedAt = cachedLastAd;
          }
        }
        
        console.log('农场数据获取成功:', data);
        console.log(`今日已观看广告: ${this.adCount}/${this.config601}`);
        
        return Promise.resolve();
      } catch (err) {
        console.error('获取农场数据异常:', err);
        return Promise.resolve();
      }
    },

    /**
     * 获取转让记录列表
     */
    async getData() {
      if (this.pageIndex > this.pageCount) {
        console.log('已加载完所有数据');
        return;
      }

      console.log(`获取记录列表，页码: ${this.pageIndex}`);
      this.isLoading = true;

      const { list, pageCount, success } = await creditdetal({
        credittype: this.credittype,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex
      });

      this.isLoading = false;
      this.pageCount = pageCount;

      if (this.pageIndex <= 1) {
        this.listArr = list;
      } else {
        this.listArr = [...this.listArr, ...list];
      }

      this.pageIndex++;
      uni.stopPullDownRefresh();
    }
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.reset();
  },

  onReachBottom() {
    console.log('触底加载更多');
    this.getData();
  }
};
</script>

<style lang="scss">
page {
  height: 100%;
  background: url('../../static/images/pages/farm/farmbg.png') no-repeat;
  background-size: 100% 100%;
  padding: 0rpx 0rpx;
  box-sizing: border-box;
}

// ✅ 广告进度条样式 - 按照设计图优化
.adProgress {
  background: rgba($color: #E8F4FD, $alpha: 0.9) !important;
  border-radius: 20rpx;
  padding: 24rpx 32rpx;
  margin: 0 24rpx;
  
  .adProgressTop {
    width: 100%;
  }
  
  // 播放图标样式
  .adIcon {
    position: relative;
    width: 56rpx;
    height: 56rpx;
    margin-right: 16rpx;
    
    .adIconInner {
      width: 100%;
      height: 100%;
      background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);
      border-radius: 50%;
      border: 3rpx solid #FF9F40;
      box-shadow: 0 2rpx 8rpx rgba(255, 159, 64, 0.3);
    }
    
    .playTriangle {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-40%, -50%);
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 8rpx 0 8rpx 14rpx;
      border-color: transparent transparent transparent #FFFFFF;
    }
  }
  
  .adTitle {
    font-size: 28rpx;
    color: #1E40AF;
    font-weight: 500;
  }
  
  .adCount {
    font-size: 28rpx;
    color: #1E40AF;
    font-weight: 600;
    
    &.text-green {
      color: #4CAF50;
    }
  }
  
  // 进度条样式
  .progressBar {
    height: 16rpx;
    background: #BFDBFE;
    border-radius: 8rpx;
    overflow: hidden;
    margin-top: 16rpx;
    
    .progressFill {
      height: 100%;
      background: linear-gradient(90deg, #3B82F6 0%, #60A5FA 50%, #93C5FD 100%);
      border-radius: 8rpx;
      transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.4);
    }
  }
  
  // 提示文字样式
  .adTip {
    text-align: center;
    font-size: 22rpx;
    color: #1E40AF;
    
    text {
      opacity: 0.8;
    }
  }
  
  .adTipComplete {
    text-align: center;
    font-size: 22rpx;
    color: #4CAF50;
    font-weight: 500;
  }
}

.text-green {
  color: #4CAF50;
}

.text-white {
  color: #FFFFFF;
}

.totalCount {
  height: 60rpx;
  background: rgba(34, 92, 243, 0.15) !important;
  border-radius: 30px;
}

.rewardBox {
  background: url('../../static/images/pages/farm/block_bg.png') no-repeat;
  background-size: 100% 100%;
}

.recordBox {
  background-size: 100% 100%;
  min-height: 500rpx;
}

.reciveBtn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(0deg, #3362f9 0%, #48a2ff 100%);
  border-radius: 15rpx;
}

.animationBox {
  margin-top: 20rpx;
  background: url('../../static/images/pages/farm/bg01.png') no-repeat;
  height: 420rpx;
  background-size: 100% 100%;
}

.farmState {
  width: 159rpx;
  height: 47rpx;
  background: #277511;
  border-radius: 20rpx;
  color: #fff;
}

.btnBox {
  .recBtn {
    background: url('../../static/images/pages/farm/recBtn.png') no-repeat;
    background-size: 100% 115rpx;
    height: 115rpx;
  }
}

.imgBox {
  position: relative;

  .farmState {
    position: absolute;
    bottom: 150rpx;
    left: 50%;
    transform: translate(-50%);
  }
}
</style>